#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
#include <arpa/inet.h>
#include <strings.h>
#include <sys/types.h>         
#include <sys/socket.h>
#include <pthread.h>
#include <signal.h>

#define SIP "127.0.0.1"
#define PORT 5001
int sockfd=-1;
struct sockaddr_in peer_addr={0};

void print_err(char *str,int line,int err_no){
	printf("%d,%s:%s\n",line,str,strerror(err_no));
	exit(-1);
}
void *pth_fun(){
	int ret=-1;
	char buf[100]={0};
	int peer_addr_size=0;
	while(1){
		bzero(buf,sizeof(buf));
		//接收对方发送色数据，保存对方的Ip和端口，以便应答
		 peer_addr_size=sizeof(peer_addr);
		ret=recvfrom(sockfd,buf,sizeof(buf),0,(struct sockaddr *)&peer_addr,&peer_addr_size);
		if(ret ==-1) print_err("recvfrom err:",__LINE__,errno);
		else if(ret>0){
			printf("peerip:%s,peerport:%d\n",inet_ntoa(peer_addr.sin_addr),ntohs(peer_addr.sin_port) );
			printf("%s\n",buf );
		}
	}
	return NULL;

}

int main(int argc,char **argv){
	int ret=-1;
	char buf[100]={0};
	
	// a.out ip port
	if(argc!=3){
		print_err("ip ,port neeed",__LINE__,errno);
		exit(1);
	}

	//创建套接字 ，指定UDP协议
	sockfd=socket(PF_INET,SOCK_DGRAM,0);
	if(sockfd ==-1)print_err("socket err:",__LINE__,errno);

	struct sockaddr_in addr;
	addr.sin_family=AF_INET;
	addr.sin_port=htons(PORT);
	addr.sin_addr.s_addr=inet_addr(SIP);

	ret=bind(sockfd,(struct sockaddr*)&addr,sizeof(addr));
	if(ret==-1) print_err("bind err:",__LINE__,errno);
	//次线程接收数据
	pthread_t tid;
	ret=pthread_create(&tid,NULL,pth_fun,NULL);
	if(ret!=0) print_err("pthread_create err:",__LINE__,errno);

	
	//主线程发送数据

	while(1){
		//设置对方的ip和端口
		peer_addr.sin_family=AF_INET;
		peer_addr.sin_port=htons(atoi(argv[2]));
		peer_addr.sin_addr.s_addr=inet_addr(argv[1]);
		bzero(buf,sizeof(buf));
		scanf("%s",buf);
		ret=sendto(sockfd,buf,sizeof(buf),0,(struct sockaddr *) &peer_addr,sizeof(peer_addr));
		if(ret==-1) print_err("sendto err:",__LINE__,errno);

	}


}